#!/usr/bin/env python3
"""
量化投资管理系统启动脚本
负责环境检查、依赖安装、数据库初始化等启动逻辑
"""

import os
import sys
import subprocess
import importlib
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 8):
        print("❌ Python版本过低，需要Python 3.8或更高版本")
        return False
    print(f"✅ Python版本: {sys.version}")
    return True

def check_virtual_environment():
    """检查虚拟环境"""
    venv_path = project_root / "venv"
    if not venv_path.exists():
        print("❌ 虚拟环境不存在，正在创建...")
        return False
    
    # 检查是否在虚拟环境中
    if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
        print("✅ 虚拟环境已激活")
        return True
    else:
        print("⚠️  未在虚拟环境中运行")
        return False

def activate_virtual_environment():
    """激活虚拟环境"""
    project_root = Path(__file__).parent
    venv_path = project_root / "venv"
    
    if not venv_path.exists():
        print("🔧 创建虚拟环境...")
        subprocess.run([sys.executable, "-m", "venv", str(venv_path)], check=True)
        print("✅ 虚拟环境创建完成")
    
    # 获取虚拟环境中的Python路径
    if os.name == 'nt':  # Windows
        python_path = venv_path / "Scripts" / "python.exe"
    else:  # Unix/Linux
        python_path = venv_path / "bin" / "python"
    
    if not python_path.exists():
        print(f"❌ 虚拟环境Python路径不存在: {python_path}")
        return None
    
    print(f"✅ 虚拟环境路径: {venv_path}")
    return python_path

def install_dependencies(python_path):
    """安装依赖包 - 优化版"""
    project_root = Path(__file__).parent
    requirements_file = project_root / "requirements.txt"
    
    if not requirements_file.exists():
        print("❌ requirements.txt文件不存在")
        return False
    
    print("📦 安装依赖包...")
    try:
        # 升级pip（静默模式）
        print("🔄 升级pip...")
        subprocess.run([str(python_path), "-m", "pip", "install", "--upgrade", "pip", "--quiet"], 
                      check=True, capture_output=True)
        print("✅ pip升级完成")
        
        # 安装核心依赖（优先）
        print("📦 安装核心依赖...")
        core_packages = [
            "fastapi==0.104.1",
            "uvicorn==0.24.0", 
            "python-dotenv",
            "mysql-connector-python==8.0.33",
            "numpy",
            "pandas",
            "requests",
            "aiohttp"
        ]
        
        for package in core_packages:
            try:
                subprocess.run([str(python_path), "-m", "pip", "install", package, "--quiet"], 
                              check=True, capture_output=True)
                print(f"✅ {package}")
            except subprocess.CalledProcessError:
                print(f"⚠️ {package} 安装失败，尝试从requirements.txt安装")
        
        # 安装其他依赖
        print("📦 安装其他依赖...")
        subprocess.run([str(python_path), "-m", "pip", "install", "-r", str(requirements_file), "--quiet"], 
                      check=True, capture_output=True)
        print("✅ 依赖安装完成")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        return False

def check_dependencies(python_path):
    """检查依赖包 - 优化版，只检查核心依赖"""
    # 核心依赖包（按重要性排序）
    core_packages = [
        'fastapi',      # Web框架
        'uvicorn',      # ASGI服务器
        'dotenv',       # 环境变量 (python-dotenv)
        'mysql.connector', # 数据库连接 (mysql-connector-python)
        'numpy',        # 数值计算
        'pandas',       # 数据处理
        'requests',     # HTTP请求
        'aiohttp',      # 异步HTTP
    ]
    
    # 可选依赖包（不影响核心功能）
    optional_packages = [
        'longport',     # 股票数据API
        'jwt',          # JWT处理（PyJWT）
        'bcrypt',       # 密码哈希（当前未使用）
    ]
    
    print("🔍 检查依赖包...")
    missing_core = []
    missing_optional = []
    
    # 检查核心依赖
    for package in core_packages:
        try:
            importlib.import_module(package.replace('[cryptography]', '').replace('[bcrypt]', ''))
            print(f"✅ {package}")
        except ImportError:
            print(f"❌ {package}")
            missing_core.append(package)
    
    # 检查可选依赖
    for package in optional_packages:
        try:
            importlib.import_module(package.replace('[cryptography]', '').replace('[bcrypt]', ''))
            print(f"✅ {package} (可选)")
        except ImportError:
            print(f"⚠️ {package} (可选，缺失)")
            missing_optional.append(package)
    
    # 只报告核心依赖缺失
    if missing_core:
        print(f"❌ 缺失的核心包: {', '.join(missing_core)}")
        return False
    
    if missing_optional:
        print(f"⚠️ 缺失的可选包: {', '.join(missing_optional)} (不影响核心功能)")
    
    print("✅ 依赖检查完成")
    return True

def check_environment():
    """检查环境变量"""
    print("🔧 检查环境变量...")
    
    # 手动加载.env文件
    project_root = Path(__file__).parent
    env_file = project_root / ".env"
    if env_file.exists():
        print("📄 加载.env文件...")
        with open(env_file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    os.environ[key] = value
        print("✅ .env文件加载完成")
    
    # 导入配置类进行验证
    try:
        sys.path.insert(0, str(project_root))
        from app_config import get_config
        config = get_config()
        
        if config.validate_longport_config():
            print("✅ LongPort API配置正确")
            return True
        else:
            print("❌ LongPort API配置不完整")
            return False
    except Exception as e:
        print(f"❌ 配置验证失败: {e}")
        return False

def initialize_database():
    """初始化数据库"""
    print("🗄️ 初始化数据库...")
    
    try:
        from database.init import initialize_database_sync
        success = initialize_database_sync()
        if success:
            print("✅ 数据库初始化成功")
            return True
        else:
            print("⚠️ 数据库初始化失败，但继续启动")
            return False
    except Exception as e:
        print(f"⚠️ 数据库初始化异常: {e}")
        return False

def start_server(python_path):
    """启动服务器"""
    project_root = Path(__file__).parent
    
    print(f"\n🌐 启动量化投资管理系统: http://0.0.0.0:8000")
    print("📚 API文档: http://localhost:8000/docs")
    print("📖 交互式文档: http://localhost:8000/redoc")
    print("💾 缓存功能: 已启用")
    print("👥 用户管理: 已启用")
    print("📈 股票分析: 已启用")
    print("🔧 健康检查: http://localhost:8000/api/health")
    print("按 Ctrl+C 停止服务器")
    print("=" * 50)
    
    try:
        # 启动app.py
        subprocess.run([
            str(python_path), "-m", "uvicorn", "app:app",
            "--host", "0.0.0.0",
            "--port", "8000",
            "--reload"
        ], cwd=str(project_root))
    except KeyboardInterrupt:
        print("\n🛑 服务器已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")

def main():
    """主函数 - 优化的启动流程"""
    print("🚀 启动量化投资管理系统...")
    print("💾 整合版本：用户管理 + 股票分析")
    print("=" * 50)
    
    # 1. 检查Python版本
    if not check_python_version():
        return
    
    # 2. 检查虚拟环境
    python_path = None
    if not check_virtual_environment():
        python_path = activate_virtual_environment()
        if not python_path:
            return
    else:
        python_path = sys.executable
    
    # 3. 快速启动流程
    print("\n🔄 快速启动服务器...")
    try:
        # 快速依赖检查（只检查核心包）
        if not check_dependencies(python_path):
            print("📦 安装缺失的依赖...")
            if not install_dependencies(python_path):
                print("❌ 依赖安装失败，但尝试继续启动")
        
        # 检查环境（简化版）
        if not check_environment():
            print("⚠️ 环境检查失败，但尝试继续启动")
        
        # 初始化数据库（非阻塞）
        print("🗄️ 初始化数据库...")
        initialize_database()
        
        # 启动服务器
        start_server(python_path)
        
    except Exception as e:
        print(f"❌ 启动过程中发生错误: {e}")
        print("💡 提示：请检查数据库连接和配置文件")

if __name__ == '__main__':
    main() 